#!/bin/bash

# 1. 安装依赖
echo "安装项目依赖..."
npm install

# 2. 构建项目
echo "构建项目..."
npm run build

# 3. 安装和配置PM2
echo "配置PM2..."
npm install -g pm2

# 创建PM2配置文件
cat > ecosystem.config.js << EOF
module.exports = {
  apps: [{
    name: 'chat-wise',
    script: 'npm',
    args: 'start',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }]
}
EOF

# 4. 启动应用
echo "启动应用..."
pm2 start ecosystem.config.js

# 5. 配置Nginx
echo "配置Nginx..."
sudo cat > /etc/nginx/conf.d/chat-wise.conf << EOF
upstream nextjs_upstream {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    keepalive 64;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://nextjs_upstream;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF

# 6. 重启Nginx
echo "重启Nginx..."
sudo nginx -s reload

# 7. 安装和启动Redis
echo "安装和启动Redis..."
sudo apt-get update
sudo apt-get install redis-server -y
sudo systemctl start redis-server
sudo systemctl enable redis-server

# 8. 设置基本监控
echo "配置监控..."
npm install -g node-exporter
node-exporter &

# 9. 保存PM2进程列表
pm2 save

# 10. 设置开机自启动
pm2 startup

echo "部署完成！"
echo "请确保已经正确设置了域名解析和SSL证书"
echo "访问 http://example.com 检查应用是否正常运行"